﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using FantastPlatform.Core.Configurations;
using FantastPlatform.Core.Extensions;
using FantastPlatform.Core.JsonEntities;
using FantastPlatform.Core.Properties;
using System.Web.Mvc;
using System.Web.Script.Serialization;
using System.Text;
using System.Xml;
using System.IO;
using System.Reflection;
using FantastPlatform.Community.IService;
using FantastPlatform.Framework;
using FantastPlatform.Framework.Core;
using Yaxunsoft.CasesManagement;
using FantastPlatform.Framework.IModel;

namespace FantastPlatform.Community.UI
{
    public partial class Main : BasePage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            //try
            //{
            //    this.menudataValue.Value = Menu();

            //    int criminalcount = 0;
            //    int securitycount = 0;
            //    if (LoginEmployee != null)
            //    {
            //        if (LoginEmployee.User != null)
            //        {
            //            IList<IRole> roleList = LoginEmployee.User.Roles;
            //            DateTime? startTime = getWeekStartTime();

            //            List<ResponsibilityArea> ResponsibilityAreaList = new List<ResponsibilityArea>();
            //            IOrganization org = LoginEmployee.EmployeePosts[0].Post.Organization;
            //            getResponsibilityArea(org, ResponsibilityAreaList);

            //            List<string> roles = new List<string>();
            //            foreach (IRole role in roleList)
            //            {
            //                roles.Add(role.Name);
            //            }
            //            if (roles.Contains("社区一级管理员") || roles.Contains("管理员"))
            //            {
            //                criminalcount = getCriminalCount(null, startTime, DateTime.Now);
            //                securitycount = getSecurityCount(null, startTime, DateTime.Now);
            //            }
            //            else
            //            {
            //                foreach (ResponsibilityArea area in ResponsibilityAreaList)
            //                {
            //                    criminalcount += getCriminalCount(area.Id, startTime, DateTime.Now);
            //                    securitycount += getSecurityCount(area.Id, startTime, DateTime.Now);
            //                }
            //            }
            //        }
            //        promptCount.InnerText = getPromptWorkLog(LoginEmployee.Id) + "条";
            //        criminalCount.InnerText = criminalcount + "件";
            //        securityCount.InnerText = securitycount + "件";
            //    }
            //    else
            //    {
            //        Response.Redirect(AppUrl + "/SSLLogin.aspx", true);
            //    }
            //}
            //catch (Exception ex)
            //{
            //    Response.Redirect(AppUrl + "/Error.aspx", true);
            //}
        }

        private void getResponsibilityArea(IOrganization org, List<ResponsibilityArea> areaList)
        {
            if (org.Children.Count == 0)
            {
                List<ResponsibilityArea> area = ResponsibilityAreaManager.LoadList(org.Name);
                if (area.Count > 0)
                    areaList.Add(area[0]);
            }
            else
            {
                foreach (IOrganization area in org.Children)
                {
                    getResponsibilityArea(area, areaList);
                }
            }
        }

        public string Menu()
        {
            List<JsonTreeNode> list = GetMenu();
            JavaScriptSerializer s = new JavaScriptSerializer();
            StringBuilder sb = new StringBuilder();
            s.Serialize(list, sb);
            //sb.Insert(0, "var menudata=");
            return sb.ToString();
        }

        public static List<JsonTreeNode> GetMenu()
        {
            string menuxml = System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "MenuData.xml";
            XmlDocument doc = new XmlDocument();
            doc.Load(menuxml);
            var nodes = doc.DocumentElement.SelectNodes("/MenuData/Menu");
            return ConvertXmlNodeToJsonNode(nodes);
        }

        private static List<JsonTreeNode> ConvertXmlNodeToJsonNode(XmlNodeList nodes)
        {
            List<JsonTreeNode> treenodelist = new List<JsonTreeNode>();
            foreach (XmlNode node in nodes)
            {
                JsonTreeNode treenode = new JsonTreeNode();
                treenode.id = node.Attributes["id"].Value;
                treenode.text = node.Attributes["text"].Value;
                treenode.value = node.Attributes["url"].Value;
                treenode.isexpand = node.Attributes["isexpand"].Value == "true";
                treenode.showcheck = false;
                treenode.complete = true;
                treenode.hasChildren = node.ChildNodes != null && node.ChildNodes.Count > 0;

                if (treenode.hasChildren)
                {
                    treenode.ChildNodes.AddRange(ConvertXmlNodeToJsonNode(node.ChildNodes));
                }
                treenodelist.Add(treenode);
            }
            return treenodelist;
        }

        private string getPromptWorkLog(int policeId)
        {
            IWorkLogService workLogService = ServiceFactory.CreateService<IWorkLogService>();
            ConditionGroup group = new ConditionGroup();
            Condition enableCondition = new Condition() { Type = typeof(bool).FullName, Field = "Enable", Value1 = true };
            Condition condition1 = new Condition() { Type = typeof(bool).FullName, Field = "IsPrompt", Value1 = true };
            Condition condition2 = new Condition() { Type = typeof(int).FullName, Field = "PoliceMan.Id", Value1 = policeId };
            group.Conditions.Add(enableCondition);
            group.Conditions.Add(condition1);
            group.Conditions.Add(condition2);
            int totalcount = 0;
            workLogService.Search(group, null, 1, int.MaxValue, out totalcount);
            return totalcount.ToString();
        }

        private int getCriminalCount(int? responsibilityAreaId, DateTime? startTime, DateTime? endTime)
        {
            CaseMainLineCondition condition = new CaseMainLineCondition();
            condition.ResponsibilityAreaId = responsibilityAreaId;
            condition.CaseCategoryId = 2;
            int totalCount = 0;
            List<CaseMainLine> list = CaseMainLineManager.LoadList(condition, 1, int.MaxValue, out totalCount);
            List<CaseMainLine> caseList = (from l in list
                                           where l.CaseHappendTimeLower > startTime && l.CaseHappendTimeLower <= endTime
                                           select l).ToList();
            return caseList.Count;
        }

        private int getSecurityCount(int? responsibilityAreaId, DateTime? startTime, DateTime? endTime)
        {
            CaseMainLineCondition condition = new CaseMainLineCondition();
            condition.ResponsibilityAreaId = responsibilityAreaId;
            condition.CaseCategoryId = 4;
            int totalCount = 0;
            List<CaseMainLine> list = CaseMainLineManager.LoadList(condition, 1, int.MaxValue, out totalCount);
            List<CaseMainLine> caseList = (from l in list
                                           where l.CaseHappendTimeLower > startTime && l.CaseHappendTimeLower <= endTime
                                           select l).ToList();
            return caseList.Count;
        }

        private DateTime? getWeekStartTime()
        {
            DateTime now = DateTime.Now;
            DayOfWeek weekDay = now.DayOfWeek;
            if (weekDay == 0)
                weekDay = DayOfWeek.Sunday;
            DateTime startTime = now.AddDays(-Convert.ToInt32(weekDay) + 1).Date;
            return startTime;
        }
    }
}